package com.sophossystems.client.asmon.dao.spring;

import java.sql.SQLException;
import java.util.List;

import com.sophossystems.client.asmon.dao.ZonaDao;
import com.sophossystems.client.asmon.dto.ZonaDTO;
import com.sophossystems.client.asmon.exceptions.DaoException;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Query;
import org.hibernate.transform.Transformers;
import org.springframework.orm.hibernate3.HibernateCallback;

public class ZonaDaoImpl extends AbstractDAO implements ZonaDao {

	private static Logger logger = Logger.getLogger(ZonaDaoImpl.class);

	@SuppressWarnings("unchecked")
	@Override
	public List<ZonaDTO> findAll() throws DaoException {
		List<ZonaDTO> exito = null;
		try {
			exito = (List<ZonaDTO>) getHibernateTemplate().execute(new HibernateCallback() {
				
				@Override
				public Object doInHibernate(Session session) throws HibernateException,
						SQLException {
					 final Query oQuery = session.createQuery("SELECT z.idZona as idZona, z.idDelegacion as idDelegacion, " +
					 		"z.idMunicipio as idMunicipio, z.idTipoZona as idTipoZona FROM " + getTableName()+ " z");
					 List<ZonaDTO> zonaDto = oQuery.setResultTransformer(Transformers.aliasToBean(ZonaDTO.class)).list();
					return zonaDto;
				}
			});
		} catch (Exception e) {
			logger.debug("Error findAll ZonaDaoImpl, causa: " + e.getCause());
			throw new DaoException("Error findAll ZonaDaoImpl, causa: " + e.getCause());
		}
		
		return exito;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ZonaDTO> findByIdTipoZona(final int idTipozona) throws DaoException {
		List<ZonaDTO> exito = null;
		try {
			exito = (List<ZonaDTO>) getHibernateTemplate().execute(new HibernateCallback() {
				
				@Override
				public Object doInHibernate(Session session) throws HibernateException,
						SQLException {
					 final Query oQuery = session.createQuery("SELECT z.idZona as idZona, z.idDelegacion as idDelegacion, " +
					 		"z.idMunicipio as idMunicipio, z.idTipoZona as idTipoZona FROM " + getTableName()+ " z" +
					 				" WHERE z.idTipoZona = :idTipoZona");
					 oQuery.setInteger("idTipoZona", idTipozona);
					 List<ZonaDTO> zonaDto = oQuery.setResultTransformer(Transformers.aliasToBean(ZonaDTO.class)).list();
					return zonaDto;
				}
			});
		} catch (Exception e) {
			logger.debug("Error findByIdTipoZona ZonaDaoImpl, causa: " + e.getCause());
			throw new DaoException("Error findAll ZonaDaoImpl, causa: " + e.getCause());
		}
		
		return exito;
	}
	
	public String getTableName(){
		return "Zona";
	}

}
